#include "pluginloader.h"
#include <QPluginLoader>
#include <QFile>
#include <QTextStream>
#include <qjson/parser.h>
#include <QDebug>
#include "../plugins/plugin_interface.h"
#include <QMdiSubWindow>

PluginLoader::PluginLoader(QWidget *parent, QMdiArea *mdiArea, QMenu *menu, QToolBar *toolBar) :
    m_parent(parent), m_mdiArea(mdiArea), m_menu(menu), m_toolBar(toolBar)
{
}

void PluginLoader::load()
{
    QFile file("plugins.json");
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qDebug() << QString("Can't open plugins.json, file didn't exist!");
        return;
    }

    QTextStream in(&file);
    in.setCodec("UTF-8");
    QString json = in.readAll();
    file.close();

    bool ok;
    QJson::Parser parser;
    QVariantMap conf = parser.parse(json.toUtf8(), &ok).toMap();
    QStringList plugins = conf["load"].toStringList();
    QString dir = conf["dir"].toString();
    QString extension = conf["extension"].toString();

    foreach (QString plugin, plugins) {
        QString path = dir + plugin + extension;
        QPluginLoader *loader = new QPluginLoader(path, m_parent);
        if (loader->load()) {
            PluginInterface *pi = qobject_cast<PluginInterface *>(loader->instance());
            if (pi) {
                QMdiSubWindow *window = new QMdiSubWindow;
                QWidget *widget = pi->widget();
                window->setWidget(widget);
                window->setWindowTitle(pi->name());
                window->setAttribute(Qt::WA_DeleteOnClose, false);
                m_mdiArea->addSubWindow(window);
                window->hide();

                QAction *action = new QAction(pi->icon(), pi->name(), m_parent);
                action->setToolTip(pi->description());
                m_toolBar->addAction(action);
                m_menu->addAction(action);

                QObject::connect(action, SIGNAL(triggered()), window, SLOT(show()));
                QObject::connect(action, SIGNAL(triggered()), widget, SLOT(show()));

                qDebug() << "Plugin" << plugin << "loaded";
            } else {
                qWarning() << "Plugin loader for" << path << "returned null pointer!";
            }
        } else {
            qWarning() << "Failed to load plugin" << path << ":" << loader->errorString();
        }
    }
}
